//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <string.h>
#include <stdio.h>
#include <aura.h>

#define FileName "/tmp/filetest.aura"
#define InputString "****************Hello world!!!****************"

EXTERN_C void AnsiToUnic(
            /* [out] */ Aura_PWChar desc,
            /* [in] */ char *src)
{
    while (*src) {
        *desc++ = (Aura_WChar)*src++;
    }
    *desc = 0;
}

void createsharememry()
{
    Aura_ECode ec;
    Aura_WChar name[AURA_MAX_DIR];
    Aura_Handle hSharedMemory;
    Aura_MemoryProtection protect;
    Aura_Address aAddress;
    Aura_MemorySize size;

    AnsiToUnic(name, FileName);
    size = 0x3000;

    ec = AuraSharedMemory_Create(name, size, AURA_TRUE, AURA_FALSE, &hSharedMemory);
    if(AURA_FAILED(ec)){
        return;
    }

    protect = Aura_MemoryProtection_RW;
    ec = AuraSharedMemory_Attach(hSharedMemory, protect, &aAddress);
    if(AURA_FAILED(ec)){
        goto EXIT;
    }

    printf("Input string:%s. and wait for recive\n", InputString);
    strcpy((char *)aAddress, InputString);
    getchar();

    AuraSharedMemory_Detach(hSharedMemory, aAddress);

EXIT:
    AuraSharedMemory_Destroy(hSharedMemory);

}

void opensharememery()
{
    Aura_ECode ec;
    Aura_WChar name[AURA_MAX_DIR];
    Aura_Handle hSharedMemory;
    Aura_MemoryProtection protect;
    Aura_Address aAddress;
    char szString[AURA_MAX_DIR];

    AnsiToUnic(name, FileName);
    memset(szString, 0, AURA_MAX_DIR);

    ec = AuraSharedMemory_Create(name, 0, AURA_TRUE, AURA_TRUE, &hSharedMemory);
    if(AURA_FAILED(ec)){
        return;
    }

    protect = Aura_MemoryProtection_RW;
    ec = AuraSharedMemory_Attach(hSharedMemory, protect, &aAddress);
    if(AURA_FAILED(ec)){
        goto EXIT;
    }

    printf("put a key will get the share memery data.\n");
    getchar();
    memcpy(szString, (char *)aAddress, strlen(InputString));
    printf("Get string:%s.\n", szString);


    AuraSharedMemory_Detach(hSharedMemory, aAddress);

EXIT:
    AuraSharedMemory_Destroy(hSharedMemory);
}

int main(int argc, char *argv[])
{
    if(argc > 1){
        opensharememery();
    } else{
        createsharememry();
    }

    return 0;
}

